<template>
    <div class="statistics">
        <!-- {{ popModel }} -->
        <!-- 工作提醒 -->
        <div class="w-notice">
            <div class="w-title">
                <div class="title">工作提醒</div>
                <div class="select1 base-select" @click="selectYear('params4')">
                    <div class="label">
                        {{ params4.workYear ? params4.workYear.toString() : '年份' }}
                    </div>
                    <img src="@/assets/images/downArraw.png" alt="">
                </div>
            </div>
            <div class="notice-wrap">
                <!-- 工作提醒统计 -->
                <div class="notice-item" v-for="(item, index) in noticeList" :key="item.id"
                    :style="`order: ${index * 2 + 1};`">
                    <div class="top-item">
                        <div class="icon">
                            <img :src="item.imgUrl" class="icon" alt="">
                        </div>
                        <div class="num" :style="`color:${item.color}`">
                            {{ item.num }}
                        </div>
                    </div>
                    <div class="b-title">{{ item.title }}</div>
                </div>
                <div class="line" v-for="item in 2" :style="`order:${item * 2}`"></div>
            </div>
            <div class="notice-icon">
                <img :src="work2" alt="">
            </div>

        </div>
        <!-- 工作事项 -->
        <div class="w-notice1">
            <!-- 工作事项分类统计 -->
            <div class="w-title">工作事项</div>
            <div class="notice-wrap">
                <!-- :class="[activeIndex == index ? ' notice-active' : '']" -->
                <div class="notice-item" @click="clickEvent(index)" v-for="(item, index) in noticeList2" :key="item.id"
                    :style="`order: ${index * 2 + 1};`">
                    <div class="top-item">
                        <div class="num" :style="{ color: item.color }">
                            {{ item.num }}
                        </div>
                    </div>
                    <div class="b-title">{{ item.title }}</div>
                </div>
                <div class="line" v-for="item in 2" :style="`order:${item * 2}`"></div>

            </div>
            <div class="notice-icon">
                <img :src="work1" alt="">
            </div>
            <!-- 工作事项分类标题 -->
            <div class="w-category-t">
                <img src="@/assets/images/workTipIcon.png" alt="">
                <div class="title">工作事项分类</div>
                <div class="select1 base-select" @click="selectYear('params1')">
                    <div class="label">
                        {{ params1.workYear ? params1.workYear.toString() : '年份' }}
                    </div>
                    <img src="@/assets/images/downArraw.png" alt="">
                </div>
            </div>
            <!-- 工作事项分类 -->
            <div class="w-category">
                <div class="event-list" v-if="eventList.length != 0">
                    <div class="event-item" v-for="(item, index) in eventList" :key="index">
                        <div class="xh">{{ index + 1 }}</div>
                        <div class="name">{{ item.name }}</div>
                        <div class="num"> {{ item.num }}</div>
                    </div>
                  
                </div>
                   <van-empty v-else :image-size="[120,120]"  description="暂无数据" />
            </div>
        </div>

        <!-- 业务分类统计 -->
        <div class="category-stati">
            <!-- 标题 -->
            <div class="title">业务分类统计
                <div class="select1 base-select" @click="selectYear('params2')">
                    <div class="label">
                        {{ params2.workYear ? params2.workYear.toString() : '年份' }}
                    </div>
                    <img src="@/assets/images/downArraw.png" alt="">
                </div>
            </div>
            <!-- 图表 -->
            <div class="chart-wrap">
                <chartPane :chartOption="option" id="yy1" />
            </div>
        </div>

        <!-- 部门分类统计 -->
        <div class="category-stati">
            <!-- 标题 -->
            <div class="title">
                部门分类统计
                <div class="select1 base-select" @click="selectYear('params3')">
                    <div class="label">
                        {{ params3.workYear ? params3.workYear.toString() : '年份' }}
                    </div>
                    <img src="@/assets/images/downArraw.png" alt="">
                </div>

            </div>
            <!-- 图表 -->
            <div class="chart-wrap">
                <chartPane :chartOption="option2" id="bm1" />
            </div>
        </div>
    </div>
    <!-- 时间选择器弹框 -->
    <van-popup teleport="body" v-model:show="yearShow" position="bottom">

        <van-picker title="请选择年份" v-model="popModel[currentParams]" :columns="yearColumns" @confirm="onYear"
            ref="yearRef" @cancel="yearShow = false" />
    </van-popup>
</template>

<script setup>
import dayjs from "dayjs"
import icon1 from "@/assets/images/icon1.png"
import icon2 from "@/assets/images/icon2.png"
import icon3 from "@/assets/images/icon3.png"
import work1 from "@/assets/images/work1.png"
import work2 from "@/assets/images/work2.png"
import { statusStatic, categoryStatic, unitStatics, typeStatics,approvalStatics } from "@/service/statics"

import {useUser} from "@/stores/user"
const userStore = useUser()

// 工作提醒
let params4 = reactive({
    workYear: dayjs().format('YYYY'),
})
//渲染列表
const noticeList = ref([
    {
        id: 1,
        num: '0',
        color: 'rgba(212, 48, 48, 1)',
        title: "停滞项目",
        imgUrl: icon1
    },
    {
        id: 2,
        num: '0',
        color: 'rgba(255, 195, 0, 1)',
        title: "滞后项目",
        imgUrl: icon2
    },
    {
        id: 3,
        num: '0',
        color: 'rgba(255, 141, 26, 1)',
        title: "督办项目",
        imgUrl: icon3
    }
])
//获取工作提醒请求
function getStatusStatic() {
    statusStatic(params4).then(res => {
        let target = res.data
        noticeList.value.forEach((nItem) => {
            target.forEach((tItem) => {
                if (nItem.title.indexOf(tItem.countType) > -1) {
                    nItem.num = tItem.count
                }
            })
        })
    })
}

// 工作事项
const noticeList2 = ref([
    {
        id: 1,
        num: 0,
        title: "应办事项",
        color: "rgba(73, 121, 235, 1)"
    },
    {
        id: 2,
        num: 0,
        title: "待办事项",
        color: "rgba(255, 195, 0, 1)"
    },
    {
        id: 3,
        num: 0,
        title: "已办事项",
        color: "rgba(103, 207, 0, 1)"
    }
])

function getWorkEvent() {
    let params = {
        isDeleted: 0
    }
    // 办公室的时候传3,科室长和分管领导就传approvalObjectId
    if (userStore.userInfo.userType == 'thirdLd') {
        params.approvalLevel = 3
    } else {
        params.approverObjectId = userStore.userInfo.userId
    }
    // params.approverObjectId = userStore.userInfo.userId
    approvalStatics(params).then(res => {
        if (res.code == 0) {
            res.data.forEach(item => {
                if (item.APPROVAL_STATUS == '待审批') {
                    noticeList2.value[1].num = item.APPROVAL_COUNT
                } else if (['已拒绝', '已批准'].includes(item.APPROVAL_STATUS)) {
                    noticeList2.value[2].num += item.APPROVAL_COUNT
                }
            })
            noticeList2.value[0].num = noticeList2.value[1].num + noticeList2.value[2].num
        }
    })
}
const activeIndex = ref(0)
function clickEvent(index) {
    activeIndex.value = index
}

// 工作事项分类
let eventList = ref([])
let params1 = reactive({
    workYear: dayjs().format('YYYY'),
})
function getEventStatic() {
    categoryStatic(params1).then(res => {
        eventList.value = res.data.map((item, index) => {
            return {
                id: item.id,
                name: item.workCategory,
                num: item.count
            }
        })
        // const result = res.data.flatMap(item => {
        //     if (item.workCategory) {
        //         return item.workCategory.split('\n').map(category => ({
        //             workCategoryCount: item.workCategoryCount,
        //             workCategory: category.trim()
        //         }));
        //     } else {
        //         return item;
        //     }
        // })
        // const mapping = {
        //     "区府实事项目": ["区府实事项目"],
        //     "区委重点工作": ["区委、区政府重点工作"],
        //     "区政府重点工作": ["区政府重点工作", "区政府主要领导明确（林长办）"],
        //     "区委主要领导明确任务": ["区委主要领导明确任务"],
        //     "市局明确任务": ["市局明确任务", "市局明确任务（120座公厕改造）"],
        //     "已纳入政治监督清单": ["已纳入政治监督清单"],
        //     "条线重要工作": ["条线重要工作"],
        //     "重要工作": ["重要工作"]
        // };
        // const updatedCategories = { ...eventObj.value };
        // result.forEach(item => {
        //     let matched = false;
        //     if (item.workCategory) {
        //         for (const [category, keywords] of Object.entries(mapping)) {
        //             if (keywords.some(keyword => item.workCategory.includes(keyword))) {
        //                 updatedCategories[category] += item.workCategoryCount;
        //                 matched = true;
        //                 break;
        //             }
        //         }
        //     }

        //     if (!matched) {
        //         updatedCategories["其它任务"] += item.workCategoryCount || 0;
        //     }
        // });
        // eventList.value = Object.entries(updatedCategories).map(([name, num], index) => ({
        //     id: index + 1,
        //     name,
        //     num
        // }));
    })
}

// 业务分类统计
// echarts的option
let option = ref({});
let params2 = reactive({
    workYear: dayjs().format('YYYY'),
})
function getTypeStatics() {
    typeStatics(params2).then(res => {
        const result = res.data.reduce((acc, item) => {
            // 初始化 businessType
            if (!acc[item.businessType]) {
                acc[item.businessType] = { normal: 0, delayed: 0, stagnant: 0, finished: 0 };
            }
            // 根据工作状态更新计数
            if (item.workStatus === "正常") {
                acc[item.businessType].normal += item.count;
            } else if (item.workStatus === "滞后") {
                acc[item.businessType].delayed += item.count;
            } else if (item.workStatus === "停滞") {
                acc[item.businessType].stagnant += item.count;
            } else if (item.workStatus === "完成") {
                acc[item.businessType].finished += item.count;
            }
            return acc;
        }, {});
        const resultArray = Object.entries(result).map(([businessType, counts]) => [
            businessType,
            counts.normal,
            counts.delayed,
            counts.stagnant,
            counts.finished
        ]);
        let xAxis = []
        // 正常
        let normal = []
        // 滞后
        let delayed = []
        // 停滞
        let stagnant = []
        // 完成
        let finished = []
        resultArray.forEach(i => {
            i.forEach((k, index) => {
                if (index == 0) {
                    xAxis.push(k)
                }
                if (index == 1) {
                    normal.push(k)
                }
                if (index == 2) {
                    delayed.push(k)
                }
                if (index == 3) {
                    stagnant.push(k)
                }
                if (index == 4) {
                    finished.push(k)
                }
            })
        })
        option.value = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                right: "1%",
                itemStyle: {
                    borderRadius: 0
                },
                icon: "rect",
                itemWidth: 12,
                itemHeight: 12,
                show: true,
                data: ['正常项目', '滞后项目', '停滞项目', '完成项目']
            },
            grid: {
                top: "20%",
                left: '3%',
                right: '4%',
                bottom: '0',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: xAxis,
                axisTick: {
                    show: false
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(229, 229, 229, 1)'
                    }
                },
                axisLabel: {
                    interval: 0, // 设置为 0 表示全部显示
                    formatter: function (value) {
                        return value.length > 4 ? value.substring(0, 4) + '...' : value;
                    },
                    rotate: 45, // 标签旋转 45 度
                    overflow: 'truncate', // 超出部分显示省略号
                    color: 'rgba(118, 118, 118, 1)'
                }
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    show: false
                },
                axisLabel: {
                    color: 'rgba(118, 118, 118, 1)'
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(118, 118, 118, 1)'
                    }
                }
            },
            series: [
                {
                    name: '正常项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(8, 173, 255, 1)'
                    },
                    data: normal
                },
                {
                    name: '滞后项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(255, 195, 0, 1)'
                    },
                    data: delayed
                },
                {
                    name: '停滞项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(212, 48, 48, 1)',
                        borderRadius: [5, 5, 0, 0] // 圆角
                    },
                    data: stagnant
                },
                {
                    name: '完成项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: '#67C23A',
                        borderRadius: [5, 5, 0, 0] // 圆角
                    },
                    data: finished
                }
            ]
        }
    })
}

// 部门分类统计
let option2 = ref({})
let params3 = reactive({
    workYear: dayjs().format('YYYY'),
})
function getUnitStatics() {
      unitStatics(params3).then(res => {
        const result = res.data.reduce((acc, item) => {
            // 初始化 businessType
            if (!acc[item.businessUnit]) {
                acc[item.businessUnit] = { normal: 0, delayed: 0, stagnant: 0, finished: 0 };
            }
            // 根据工作状态更新计数
            if (item.workStatus === "正常") {
                acc[item.businessUnit].normal += item.count;
            } else if (item.workStatus === "滞后") {
                acc[item.businessUnit].delayed += item.count;
            } else if (item.workStatus === "停滞") {
                acc[item.businessUnit].stagnant += item.count;
            } else if (item.workStatus === "完成") {
                acc[item.businessUnit].finished += item.count;
            }
            return acc;
        }, {});
        const resultArray = Object.entries(result).map(([businessUnit, counts]) => [
            businessUnit,
            counts.normal,
            counts.delayed,
            counts.stagnant,
            counts.finished
        ]);
        let xAxis = []
        // 正常
        let normal = []
        // 滞后
        let delayed = []
        // 停滞
        let stagnant = []
        // 完成
        let finished = []
        resultArray.forEach(i => {
            i.forEach((k, index) => {
                if (index == 0) {
                    xAxis.push(k)
                }
                if (index == 1) {
                    normal.push(k)
                }
                if (index == 2) {
                    delayed.push(k)
                }
                if (index == 3) {
                    stagnant.push(k)
                }
                if (index == 4) {
                    finished.push(k)
                }
            })
        })
        option2.value = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                right: "1%",
                itemStyle: {
                    borderRadius: 0
                },
                icon: "rect",
                itemWidth: 12,
                itemHeight: 12,
                show: true,
                data: ['正常项目', '滞后项目', '停滞项目', '完成项目']
            },
            grid: {
                top: "20%",
                left: '3%',
                right: '4%',
                bottom: '0',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: xAxis,
                axisTick: {
                    show: false
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(229, 229, 229, 1)'
                    }
                },
                axisLabel: {
                    interval: 0, // 设置为 0 表示全部显示
                    formatter: function (value) {
                        return value.length > 4 ? value.substring(0, 4) + '...' : value;
                    },
                    rotate: 45, // 标签旋转 45 度
                    overflow: 'truncate', // 超出部分显示省略号
                    color: 'rgba(118, 118, 118, 1)'
                }
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    show: false
                },
                axisLabel: {
                    color: 'rgba(118, 118, 118, 1)'
                },
                axisLine: {
                    lineStyle: {
                        color: 'rgba(118, 118, 118, 1)'
                    }
                }
            },
            series: [
                {
                    name: '正常项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(8, 173, 255, 1)'
                    },
                    data: normal
                },
                {
                    name: '滞后项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(255, 195, 0, 1)'
                    },
                    data: delayed
                },
                {
                    name: '停滞项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: 'rgba(212, 48, 48, 1)',
                        borderRadius: [5, 5, 0, 0] // 圆角
                    },
                    data: stagnant
                },
                {
                    name: '完成项目',
                    type: 'bar',
                    stack: '总量',
                    barWidth: '20%',
                    itemStyle: {
                        color: '#67C23A',
                        borderRadius: [5, 5, 0, 0] // 圆角
                    },
                    data: finished
                }
            ]
        }
    })
}




// 时间选择
// 用来绑定对应弹出框选中的值
const popModel = ref({
    'params1': [dayjs().format('YYYY')],
    'params2': [dayjs().format('YYYY')],
    'params3': [dayjs().format('YYYY')],
    'params4':[dayjs().format('YYYY')],
})
const currentParams = ref('params1')
function selectYear(params) {
    currentParams.value = params
    yearShow.value = true
}
const yearShow = ref(false)
const yearColumns = ref([])
const yearRef = ref(null)
function onYear() {
    const { value } = yearRef.value.getSelectedOptions()[0]
    // 三个时间选择器根据不同的模块赋值对应的请求参数
    if (currentParams.value == 'params1') {
        // 工作事项分类统计
        params1.workYear = value
        getEventStatic()
    } else if (currentParams.value == 'params2') {
        // 业务分类统计
        params2.workYear = value
        getTypeStatics()
    } else if(currenParams == 'params3') {
        // 部门分类统计 
        params3.workYear = value
        getUnitStatics()
    }else if(currenParams == 'params4') {
        // 工作提示
        params4.workYear = value
        getUnitStatics()
    }
    popModel.value[currentParams.value] = [value]
    yearShow.value = false
}
// 创建时间选择器
function createYearColumn() {
    const currentYear = new Date().getFullYear(); // 获取当前年份
    for (let i = -2; i <= 0; i++) {
        const year = currentYear + i; // 计算当前年及之前两年
        yearColumns.value.push({ text: year.toString(), value: year.toString() });
    }
}


onMounted(() => {
    getTypeStatics()
    getStatusStatic()
    getEventStatic()
    getUnitStatics()
    createYearColumn()
    getWorkEvent()
})
</script>

<style lang="scss" scoped>
.statistics {
    height: calc(100vh - 47px - 140px);
    overflow: auto;
    padding: 0 20px;
    box-sizing: border-box;
}

.w-notice {
    margin-bottom: 20px;
    position: relative;
    height: 276px;
    padding: 30px 24px;
    box-sizing: border-box;
    border-radius: 30px;
    background: rgba(255, 255, 255, 1);

    .w-title {
        display: flex;
        align-items: center;
        font-size: 30px;
        color: rgba(51, 51, 51, 1);
    }

    .notice-wrap {
        position: absolute;
        z-index: 3;
        bottom: 40px;
        left: 40px;
        width: 92%;
        padding: 0 40px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .notice-item {
            .top-item {
                display: flex;
                align-items: center;

                .icon {
                    position: relative;
                    width: 86px;
                    height: 86px;
                }

                .num {
                    font-size: 44px;
                }
            }

            .b-title {
                font-size: 28px;
                color: rgba(128, 128, 128, 1);
            }
        }

        .line {
            margin: 0 10px;
            width: 2px;
            height: 100px;
            background: rgba(220, 240, 250, 1);
        }
    }

    .notice-icon {
        position: absolute;
        right: 20px;
        top: 0;
        z-index: 2;

        img {
            opacity: 0.5;
            height: 200px;
            width: 200px;
        }
    }
}


.w-notice1 {
    margin-bottom: 20px;
    position: relative;
    // height: 276px;
    padding: 30px 24px;
    box-sizing: border-box;
    border-radius: 30px;
    background: rgba(255, 255, 255, 1);

    .w-title {
        font-size: 30px;
        color: rgba(51, 51, 51, 1);
    }

    .notice-wrap {
        position: relative;
        top: 40px;
        z-index: 3;
        padding: 0 40px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .notice-item {
            width: 196px;

            .top-item {
                .num {
                    text-align: center;
                    color: rgba(51, 51, 51, 1);
                    font-size: 44px;
                }
            }

            .b-title {
                text-align: center;
                font-size: 28px;
                color: rgba(128, 128, 128, 1);
            }
        }

        .line {
            margin: 0 10px;
            width: 2px;
            height: 100px;
            background: rgba(220, 240, 250, 1);
        }
    }

    .notice-icon {
        position: absolute;
        right: 60px;
        top: 20px;
        z-index: 2;

        img {
            opacity: 0.5;
            height: 160px;
            width: 160px;
        }
    }
}

.w-category-t {
    display: flex;
    align-items: center;
    margin-top: 70px;

    img {
        width: 30px;
        height: 33px;
    }

    .title {
        margin-left: 14px;
        font-size: 28px;
        color: rgba(22, 130, 245, 1)
    }
}

.w-category {
    height: 380px;
    padding: 10px 15px;
    box-sizing: border-box;
    width: 100%;
    background: linear-gradient(to bottom, #fff 30%, rgb(237, 246, 255) 70%);
    border-radius: 20px;
    margin-top: 30px;
    display: flex;
    justify-content: center;

    .event-list {
        overflow-y: auto;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;


        .xh {
            font-style: italic;
            color: rgba(166, 166, 166, 1) !important;

        }
        .event-item {
            height: 80px;
            font-size: 26px;
            display: flex;
            align-items: center;
            justify-content: space-evenly;
            width: 48%;
            color: rgba(56, 56, 56, 1);
            border-bottom: 1px solid rgba(229, 229, 229, 1);

            .xh {
                width: 10%;
            }

            .name {
                width: 70%;
                overflow: hidden;
                /* 隐藏超出元素的内容 */
                white-space: nowrap;
                /* 防止文本换行 */
                text-overflow: ellipsis;
                /* 使用省略号表示被裁剪的文本 */


            }
        }

        //.event-item:nth-last-child(1),
        //.event-item:nth-last-child(2) {
        //    border: none !important;
        //}


    }

}

.category-stati {
    padding: 30px 20px 0 20px;
    position: relative;
    // height: 500px;
    opacity: 1;
    border-radius: 30px;
    background: rgba(255, 255, 255, 1);

    .title {
        display: flex;
        align-items: center;
        //position: absolute;
        color: rgba(51, 51, 51, 1);
        font-size: 30px;
        margin-bottom: 10px;
    }

    .chart-wrap {
        width: 100%;
        height: calc(500px - 35px);
    }
}

.notice-active {

    background-image: url("@/assets/images/activeBg.png");
    background-size: 100% 100%;
}

.select1 {
    font-size: 28px;
    // width: 190px;
    height: 60px;
    border-radius: 20px;
    background: rgba(248, 248, 250, 1);
    border: none;
    box-shadow: none;
}

.base-select {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-sizing: border-box;
    width: 120px;
    margin-left: 20px;

    img {
        height: 6px;
        width: 12px;
    }
}
</style>